<template>
  <!-- 搜索 -->
  <div class="my-wbox">
    <!-- 搜索 -->
    <MySearch
      :searchData="searchData"
      @listenClick="listenClick"
      :isSearch="isSearch"
    >
      <template #townId>
        <div class="lh32">
          <el-select
            v-model="townId"
            placeholder="请选择乡镇"
            clearable
            size="large"
            :disabled="
              loading || userInfo.roleId == '4' || userInfo.roleId == '5'
            "
            @change="onSlotSearch('townId')"
          >
            <el-option
              :label="v.label"
              :value="v.value"
              v-for="v in townIdArr"
              :index="v.value"
            />
          </el-select>
        </div>
      </template>
      <template #countryId>
        <div class="lh32">
          <el-select
            v-model="countryId"
            placeholder="请选择村"
            size="large"
            clearable
            :disabled="loading || userInfo.roleId == '5'"
            @change="onSlotSearch('countryId')"
          >
            <el-option
              :label="v.label"
              :value="v.value"
              v-for="v in countryIdArr"
              :index="v.value"
            />
          </el-select>
        </div>
      </template>
    </MySearch>
    <!-- 表格 -->
    <MyTable :tableData="tableData" @listenClick="listenClick">
      <template #default="{ slotData, slotColumn }">
        <div v-if="slotColumn.prop === 'address'">
          {{ slotData.townName }}{{ slotData.countryName
          }}{{ slotData.groupName }}
        </div>
      </template>
    </MyTable>

    <!-- 数据转移窗口 -->
    <TransferDialog
      :isShowDialog="isShowDialog"
      :dialogData="dialogData"
    ></TransferDialog>

    <!-- 批量数据转移窗口 -->
    <BatchTransferDialog :isShowBDialog="isShowBDialog"></BatchTransferDialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useStore } from '@/store'
import { FunTime } from '@/global/methods'
import MyTable from '@/components/MyTable.vue'
import MySearch from '@/components/MySearch.vue'
import { ParentSearch, ParentTable } from '@/interface/index'
import { getAreaListApi } from '@/views/account/api/accountApi'
import { SelectObj } from '@/interface/index'
import { useRouter } from 'vue-router'
import {
  getUserInfo,
  setSearchFamily,
  getSearchFamily,
  removeSearchFamily,
} from '@/global/session'
import TransferDialog from './components/TransferDialog.vue'
import BatchTransferDialog from './components/BatchTransferDialog.vue'
import http from '@/http/http'
import { ElMessage } from 'element-plus'
const router = useRouter()
const store = useStore()
let userInfo = reactive({ roleId: '', townId: '', countryId: '', roleAuth: '' })
userInfo = JSON.parse(getUserInfo() as string)
//监听加载
const loading = computed(() => {
  return store.getters['loading/getLoad']
})
let searchInfo = getSearchFamily() //搜索条件

// 搜索是否触发
const isSearch = ref<boolean>(false)
//封装的搜索
const searchData = reactive<ParentSearch>({
  searchForm: [
    {
      key: 'townId',
      styleType: 'slot',
      label: '乡镇:',
      labelShow: true,
      value: '',
    },
    {
      key: 'countryId',
      styleType: 'slot',
      label: '村:',
      labelShow: true,
      value: '',
    },
    {
      key: 'groupName',
      styleType: 'input',
      label: '组:',
      labelShow: true,
      value: '',
      placeholder: '请输入组名',
    },
    {
      key: 'userPhone',
      styleType: 'input',
      label: '网格干部手机号:',
      labelShow: true,
      value: '',
      placeholder: '请输入网格干部手机号',
    },
    {
      key: 'name',
      styleType: 'input',
      label: '姓名:',
      labelShow: true,
      value: '',
      placeholder: '请输入姓名',
    },
    {
      key: 'phone',
      styleType: 'input',
      label: '手机号:',
      labelShow: true,
      value: '',
      placeholder: '请输入手机号',
    },
    {
      key: 'daterange',
      styleType: 'date',
      label: '最后录入时间:',
      labelShow: true,
      type: 'daterange',
      format: 'YYYY-MM-DD',
      value: '',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
    },
    {
      key: 'content',
      styleType: 'input',
      label: '宣传内容:',
      labelShow: true,
      value: '',
      placeholder: '请输入宣传内容',
      inputWidth: '400px',
    },
  ],
  searchBtn: [
    {
      name: 'onTransfer',
      type: 'primary',
      text: '数据转移',
      hide(row: any): boolean {
        return userInfo.roleId == '4'
      },
    },
    {
      name: 'onBatchTransfer',
      type: 'primary',
      text: '批量数据转移',
      hide(row: any): boolean {
        return userInfo.roleId == '4'
      },
    },
    { name: 'onExportAll', type: 'primary', text: '全部导出' },
  ],
})
//封装的表格
const tableData = reactive<ParentTable>({
  //表格的一些数据
  listApi: '/manage/admin/familyInfo/pageList', //列表搜索接口
  listHttp: 'post', //列表接口方法
  search: {}, //搜索条件
  column: [
    //表头
    { prop: 'name', label: '户主', align: 'left' },
    { prop: 'address', label: '常驻地址', slot: true },
    { prop: 'phone', label: '手机号' },
    { prop: 'memberNames', label: '家庭成员', tooltip: true },
    { prop: 'createTime', label: '最后录入时间', tooltip: true },
  ],
  columnBtn: {
    //操作按钮
    label: '操作',
    align: 'center',
    width: '250',
    btn: [
      { name: 'onRouter', text: '详情' },
      { name: 'onExport', text: '导出' },
      {
        name: 'myApi',
        text: '删除',
        api: '/manage/admin/familyInfo/deleteById',
        http: 'deleteFormUrl',
        confirm: true,
        confirmText: 'name',
        refresh: true,
        params: { id: '' },
      },
    ],
  }, //表按钮
  index: true, //true 显示序号
  noRender: true,
  selection: true,
})
//插槽的搜索  keySlot传入对应的key
const onSlotSearch = (keySlot: string) => {
  let obj = searchData.searchForm?.find((t) => t.key === keySlot)
  if (obj) {
    if (keySlot === 'townId') {
      obj.value = townId.value
      countryId.value = ''
      if (searchData?.searchForm) {
        searchData.searchForm[1].value = ''
      }
      if (townId.value) {
        onAreaList({ id: townId.value }, 5)
      }
    } else if (keySlot === 'countryId') {
      obj.value = countryId.value
    }
    // isSearch.value = !isSearch.value //是否触发搜索
  }
}
//列表搜索
const onSearch = (val: any) => {
  if (val?.daterange?.length > 0) {
    val.startDate = FunTime(val.daterange[0])
    val.endDate = FunTime(val.daterange[1])
  }
  tableData.search = val
  tableData.noRender = false //显示表格
  //刷新表格
  store.commit('refresh/setRefresh', !store.getters['refresh/getRefresh'])
  //yaohui
  //把搜索条件记录一下
  setSearchFamily(JSON.stringify(tableData.search))
}
//列表搜索重置 清空插槽里面的内容
const onSearchClear = (val: any) => {
  if (
    userInfo.roleId == '1' ||
    userInfo.roleId == '2' ||
    userInfo.roleId == '3'
  ) {
    // // "roleId": //角色id 1、超级管理员  2、市级管理员 3、市级督察员
    townId.value = ''
    countryId.value = ''
  } else if (userInfo.roleId == '4') {
    // "roleId": //角色id  4、镇级管理员  5、村级管理员
    countryId.value = ''
    val.townId = townId.value
  } else if (userInfo.roleId == '5') {
    //"roleId": //角色id   5、村级管理员
    val.townId = townId.value
    val.countryId = countryId.value
  }
  removeSearchFamily() //清除搜索条件
  onSearch(val)
}
//详情
const onRouter = (row: any) => {
  //把搜索条件记录一下
  setSearchFamily(JSON.stringify(tableData.search))
  router.push({
    name: 'familyDetail',
    query: { name: row.name, phone: row.phone },
  })
}
//全部导出
const onExportAll = () => {
  store.commit('loading/setLoad', true)
  let params = tableData.search
  onFunApi('/manage/admin/familyInfo/exportAll', params)
}
//单个导出
const onExport = (val: any) => {
  store.commit('loading/setLoad', true)
  let params = {
    name: val.name,
    phone: val.phone,
  }
  onFunApi('/manage/admin/familyInfo/exportOne', params)
}
const onFunApi = async (url: string, params: any) => {
  try {
    let res = await http.post(url, params)
    if (res?.code === 0 && res.data) {
      window.open(res.data)
    }
    store.commit('loading/setLoad', false)
  } catch {
    store.commit('loading/setLoad', false)
  }
}
//分页 一页多少条数
const onListenPageSize = (val: number) => {
  tableData.search.pageSize = val
}
//分页  当前页码
const onListenPageIndex = (val: number) => {
  tableData.search.currentPage = val
}

const isShowBDialog = ref<boolean>(false) //数据转移弹窗是否出现
const isShowDialog = ref<boolean>(false) //数据转移弹窗是否出现
const dialogData: any = ref([]) //传给弹窗的数据
const selection: any = ref([])
//数据转移
const onTransfer = () => {
  if (selection.value.length == 0) {
    ElMessage({ type: 'warning', message: '请选择需要转移的户主' })
  } else {
    isShowDialog.value = !isShowDialog.value
    const arr = selection.value.map((item: any) => item.id)
    dialogData.value = arr
  }
}
const onSelectionChange = (val: any) => {
  selection.value = val
}

//批量数据转移
const onBatchTransfer = () => {
  isShowBDialog.value = !isShowBDialog.value
}

//定义方法对象 注意定义的方法 必须在上面已经申明 所以建议objFun申明和 listenClick方法 写在页面最下面
const objFun = {
  onSearch: onSearch,
  onSearchClear: onSearchClear,
  onRouter: onRouter,
  onExportAll: onExportAll,
  onExport: onExport,
  onListenPageSize: onListenPageSize,
  onListenPageIndex: onListenPageIndex,
  onTransfer: onTransfer,
  onSelectionChange: onSelectionChange,
  onBatchTransfer: onBatchTransfer,
}
// 监听子级表格  传过来的方法禁用
const listenClick = (name: string, val: any) => {
  objFun[name](val)
}
//获取所有乡镇
let townIdArr = ref<SelectObj[]>([]) //乡镇
let countryIdArr = ref<SelectObj[]>([]) //存
const onAreaList = async (params: any, num: number) => {
  try {
    let res = await getAreaListApi(params)
    if (res?.code === 0) {
      let arr: SelectObj[] = []
      res.data.forEach((t) => {
        if (userInfo.roleId == '3' && num === 4) {
          //督察员
          let roleAuth = userInfo.roleAuth.split(',')
          roleAuth.forEach((v) => {
            if (t.areaCode === v) {
              arr.push({ label: t.name, value: t.areaCode })
            }
          })
        } else {
          arr.push({ label: t.name, value: t.areaCode })
        }
      })
      if (num === 4) {
        townIdArr.value = arr
      } else {
        countryIdArr.value = arr
      }
    }
  } catch {}
}
const townId = ref<string>('') //乡镇
const countryId = ref<string>('') //村组
// yaohui
if (searchInfo) {
  let searchObj = JSON.parse(searchInfo)
  searchObj.startDate1 = new Date(searchObj.startDate1)
  searchObj.endDate1 = new Date(searchObj.endDate1)
  searchData.searchForm?.forEach((t) => {
    t.value = searchObj[t.key]
  })
  tableData.search = searchObj
  townId.value = searchObj.townId
  countryId.value = searchObj.countryId

  // let { pageSize, currentPage, ...obj } = searchObj
  // tableData.search = obj

  onAreaList({ id: '0' }, 4)
  if (searchObj.townId) {
    //如果有镇  查镇下面的乡
    onAreaList({ id: searchObj.townId }, 5)
  }
  tableData.noRender = false //显示表格
} else {
  if (
    userInfo.roleId == '1' ||
    userInfo.roleId == '2' ||
    userInfo.roleId == '3'
  ) {
    onAreaList({ id: '0' }, 4)
  } else if (userInfo.roleId == '4') {
    townId.value = userInfo.townId
    onAreaList({ id: '0' }, 4)
    onAreaList({ id: userInfo.townId }, 5)
    if (searchData.searchForm) {
      searchData.searchForm[0].value = townId.value
    }
  } else if (userInfo.roleId == '5') {
    townId.value = userInfo.townId
    countryId.value = userInfo.countryId
    onAreaList({ id: '0' }, 4)
    onAreaList({ id: userInfo.townId }, 5)
    if (searchData.searchForm) {
      searchData.searchForm[0].value = townId.value
      searchData.searchForm[1].value = countryId.value
    }
  }
}
</script>
<style scoped lang="scss"></style>
